#ifndef _GWBASE_BASE_THREAD_LOCAL_H
#define _GWBASE_BASE_THREAD_LOCAL_H

#include <string.h>
#include <pthread.h>
#include <errno.h>
#include "gwbase/base/logging.h"

namespace dicom {

template <class T>
class ThreadLocal {
 public:
  ThreadLocal() {
    if (pthread_key_create(&pkey_, NULL)) {
      LOG_FATAL << "pthread_key_create() failed: " << strerror(errno);
    }
  }

  ~ThreadLocal() {
    if (pthread_key_delete(pkey_)) {
      LOG_FATAL << "pthread_key_destroy() failed: " << strerror(errno);
    }
  }

  T* Get() {
    T* obj = static_cast<T*>(pthread_getspecific(pkey_));
    return obj;
  }

  void Set(T* obj) { pthread_setspecific(pkey_, obj); }

 private:
  pthread_key_t pkey_;
};

}

#endif // _GWBASE_BASE_THREAD_LOCAL_H
